<template>
  <div class="model">
    <el-card>
      <div class="add-btn">
        <el-button type="primary" @click="addModel" v-has-permi="['cmdb:model:add']">新建模型</el-button>
        <el-button type="primary" @click="addGroup" v-has-permi="['cmdb:group:add']">新建分组</el-button>
      </div>
      <div class="content-tree">
        <ul>
          <li v-for="(cmc, index) in groupList" :key="cmc.cmc_key">
            <div>
              <div class="title-icon df ai-c">
                <span style="font-weight: 600;">{{cmc.cmc_name}}</span>
                <span class="df ai-c">
                  <el-icon v-has-permi="['cmdb:model:add']" style="margin-left: 6px;cursor: pointer;" @click="groupAddL(cmc)">
                    <FolderAdd />
                  </el-icon>
                  <el-icon v-has-permi="['cmdb:group:edit']" style="margin-left: 6px;cursor: pointer;" @click="groupEditL(cmc)">
                    <Edit />
                  </el-icon>
                  <el-icon v-has-permi="['cmdb:group:delete']" style="margin-left: 6px;cursor: pointer;" @click="groupDelL(cmc)">
                    <Delete />
                  </el-icon>
                </span>
              </div>
              <div class="df fw-w content-li">
                <el-card v-for="cme in cmc.children" :key="cme.cme_key" @click="openModelDetail(cme)">
                  <div><img :src="'./cmdb/'+cme.cme_icon+'.svg'" alt="" /></div>
                  <div class="df fd-c js-sb ">
                    <span class="ov1" style="width:100px;">  
                      <el-tooltip class="box-item" effect="dark" :content="cme.cme_name" placement="top-start">
                        <span> {{cme.cme_name}}</span>
                      </el-tooltip>
                    </span>
                    <span class="ov1" style="width:100px;">{{cme.cme_key}}</span>
                  </div>
                  <div style="margin-left: 8px;">
                    <el-dropdown>
                      <span class="el-dropdown-link" style="cursor: pointer;" @click.stop="">
                        操作
                        <el-icon class="el-icon--right">
                          <arrow-down />
                        </el-icon>
                      </span>
                      <template #dropdown>
                        <el-dropdown-menu>
                          
                          <el-dropdown-item >
                            <span v-has-permi="['cmdb:model:edit']"  @click="modelEditBtn(cme)">编辑</span>
                          </el-dropdown-item>
                          <el-dropdown-item  >
                            <span v-has-permi="['cmdb:model:delete']" @click="modelDelBtn(cme)">删除</span>
                          </el-dropdown-item>
                        
                        </el-dropdown-menu>
                      </template>
                    </el-dropdown>
                  </div>
                </el-card>
              </div>
            </div>  
          </li>
        </ul>
      </div>
    </el-card>

    <!-- 模型弹框 -->
    <el-dialog v-model="modelVisible" :title="modelTitle" width="800" :close-on-click-modal="false">
      <el-form ref="ruleFormRef" style="max-width: 800px" :model="modelForm" :rules="modelRules" label-width="auto" class="demo-ruleForm" status-icon>
        <el-form-item label="唯一标识:" prop="cme_key" :rules="[{ required: true,validator: keyRules, trigger: 'blur' }]">
          <el-input v-model="modelForm.cme_key" :disabled="  modelTitle == '编辑模型'" />
        </el-form-item>
        <el-form-item label="模型名称:" prop="cme_name" :rules="[{ required: true, message: '请输入模型名称' }]">
          <el-input v-model="modelForm.cme_name" />
        </el-form-item>
        <el-form-item label="模型图标:" prop="cme_icon">
          <div class="df jc-sb" style="width: 100%;">
            <el-input v-model="modelForm.cme_icon" disabled />
            <el-button style="margin-left: 8px;" @click="modelVisibleIcon=true">选择图标</el-button>
          </div>
        </el-form-item>
        <el-form-item label="所属分组:" prop="cmc_key" :rules="[{ required: true, message: '请选择所属分组' }]">
          <el-select v-model="modelForm.cmc_key" placeholder="请选择" style="width: 100%">
            <el-option :label="item.cmc_name" :value="item.cmc_key" v-for="(item, index) in groupList" :key="item.cmc_key" @click="selectGroup(item)" />
          </el-select>
        </el-form-item>

        <el-form-item label="模型类型:" prop="cme_type" :rules="[{ required: true, message: '请选择模型类型' }]">
          <el-select v-model="modelForm.cme_type" placeholder="请选择" style="width: 100%">
            <el-option :label="'软件类型'" :value="1" @click="selectType('软件类型')" />
            <el-option :label="'硬件类型'" :value="2" @click="selectType('硬件类型')" />
          </el-select>
        </el-form-item>

        <el-form-item v-if="modelForm.cme_type==1" label="软件:" prop="serviceType" :rules="[{ required: true, message: '请选择软件类型' }]">
          <el-select v-model="modelForm.serviceType" placeholder="请选择" style="width: 100%">
            <el-option label="mysql" value="mysql" />
            <el-option label="redis" value="redis" />
          </el-select>
        </el-form-item>

        <el-form-item v-if="modelForm.cme_type==2" label="硬件:" prop="serviceType" :rules="[{ required: true, message: '请选择硬件类型' }]">
          <el-select v-model="modelForm.serviceType" placeholder="请选择" style="width: 100%">
            <el-option label="Windows" value="windows_server" />
            <el-option label="Linux" value="linux_server" />
            <el-option label="snmp" value="snmp" />
          </el-select>
        </el-form-item>

        <!-- <el-form-item label="监控面板:" prop="cme_monitoring">
          <el-select v-model="modelForm.cme_monitoring" placeholder="请选择" style="width: 100%">
            <el-option :label="'软件类型'" :value="1" />
            <el-option :label="'硬件类型'" :value="2" />
          </el-select>         
        </el-form-item> -->
        <el-form-item label="监控端口:" prop="cme_port">
          <el-input v-model="modelForm.cme_port" />
        </el-form-item>
      </el-form>
      <el-dialog v-model="modelVisibleIcon" width="800" title="选择图标" append-to-body :close-on-click-modal="false">
        <ul class="icon-list">
          <el-tooltip v-for="(iconName, index) in iconNames" :key="index" :content="iconName" placement="bottom" effect="light">
            <li :class="['icon-item']" @click="selectedIcon(iconName)">
              <!-- <svg-icon color="var(--el-text-color-regular)" :icon-class="iconName" /> -->
              <!-- <img :src="'/itss/assets/'+iconName+'.svg'" alt="" style="width: 40px;height: 40px;" /> -->
              <img :src="'./cmdb/'+iconName+'.svg'" alt="" style="width: 40px;height: 40px;" />
            </li>
          </el-tooltip>
        </ul>
      </el-dialog>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="modelVisible = false">关闭</el-button>
          <el-button type="primary" @click="modelEnter"> 提交 </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 模型详情 -->
    <el-drawer v-model="drawerVisible" title="模型详情" direction="rtl" size="100%">
      <drawer ref="modelDetailRef" :model_id="model_id"></drawer>
    </el-drawer>

    <!-- 分组弹框 -->
    <el-dialog v-model="groupVisible" :title="groupTitle" width="800" :close-on-click-modal="false">
      <el-form ref="GroupFormRef" style="max-width: 800px" :model="GroupForm" :rules="GroupRules" label-width="auto" class="demo-ruleForm" status-icon>
        <el-form-item label="唯一标识:" prop="cmc_key" :rules="[{ validator: keyRules, trigger: 'blur' }]">
          <el-input v-model="GroupForm.cmc_key" :disabled="  groupTitle == '编辑分组'" />
        </el-form-item>
        <el-form-item label="分组名称:" prop="cmc_name">
          <el-input v-model="GroupForm.cmc_name" />
        </el-form-item>
        <el-form-item label="排序:" prop="cmc_sort">
          <el-input v-model="GroupForm.cmc_sort" type="number" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="groupVisible = false">关闭</el-button>
          <el-button type="primary" @click="groupEnter"> 提交 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, toRefs, reactive } from 'vue';
import {keyRules} from './config'
import { modelFormType ,GroupRules } from './types';
import drawer from './components/drawer.vue';
// import icons from '@/components/IconSelect/requireIcons';
import {icons} from '@/components/IconSelect/cmdbIcons';
import {modelGroupAdd ,modelGroupEdit ,modelGroupDel ,modelGroupList ,modelAdd,modelEdit,modelDel} from '@/api/cmdb/model'
const iconNames = ref<string[]>(icons);

// 模型配置
const modelForm = ref<modelFormType>({
  cme_key: '',
  cme_name: '',
  cme_icon: '',
  cmc_key:"",
  cme_type:"",
  // cme_monitoring:"",
  // cme_port:"",
});
const modelRules = ref<any>({
  key: [
    { required: true, message: '请输入唯一标识', trigger: 'blur' }
    // { min: 3, max: 5, message: 'Length should be 3 to 5', trigger: 'blur' },
  ],
  name: [{ required: true, message: '请输入模型名称', trigger: 'blur' }]
});
const modelVisible = ref<boolean>(false);
const modelVisibleIcon = ref<boolean>(false);
const data = reactive({
  iconForm: {
    icon: ''
  },
  groupVisible:false,//分组弹框
  GroupForm:{ //分组表单
    cmc_key:"",
    cmc_name:"",
    cmc_sort:""
  },
  groupTitle:"",
  modelTitle:"",
  model_id:"",//模型中的id号

});
const { iconForm ,groupVisible ,GroupForm ,groupTitle ,modelTitle ,model_id} = toRefs(data);
const  groupList = ref<any>([])
const modelDetailRef = ref()
// 选择图标
const selectedIcon = (val:string) => {
  iconForm.value.icon = val;
  console.log(iconForm.value);
  modelForm.value.cme_icon = val;
  modelVisibleIcon.value = false;
};

const addModel = async() => {
  modelTitle.value = '新建模型'
  modelForm.value={ cme_key: '', cme_name: '',  cme_icon: '',   cmc_key:"",   cme_type:"",}
  modelVisible.value = true;
};

const ruleFormRef = ref()
/* 新建模型确认 */
const modelEnter = () => {

  ruleFormRef.value?.validate(async(flag:boolean)=>{
    console.log(flag);
    console.log(modelForm.value);
    if(flag){
      const res =  modelTitle.value == '新建模型'?await modelAdd({...modelForm.value}) :await modelEdit({...modelForm.value})
      console.log(res);
      if(res.data){
        ElMessage.success( modelTitle.value+'完成')
        await getGroupList()
      }

      modelVisible.value = false;
    }
  })
};
const modelOpter = () => {};
const addGroup = () => {
  groupTitle.value = '新建分组'
  GroupForm.value = { cmc_key:"", cmc_name:"",  cmc_sort:""}
  groupVisible.value = true
};

const GroupFormRef = ref()
// 新建分组提交
const groupEnter = ()=>{

  GroupFormRef.value?.validate(async (valid: boolean) => {
    if(valid){
      const res= groupTitle.value == '新建分组'? await modelGroupAdd({...GroupForm.value}) : await modelGroupEdit({...GroupForm.value})
    console.log(res);

    if(res.data){
      ElMessage.success(groupTitle.value+'成功')
      groupVisible.value = false
      await getGroupList()
    }
    }
  })
  console.log(GroupForm.value);

}

/* 列表中icon图标点击事件 */
const groupAddL = (row)=>{
  modelTitle.value = '新建模型'
  console.log(row);
  modelForm.value={ cme_key: '', cme_name: '',  cme_icon: '',   cmc_key:row.cmc_key,   cme_type:""}
  modelVisible.value = true

}
const groupEditL = (row)=>{
  groupTitle.value = '编辑分组'
  GroupForm.value = { cmc_key:row.cmc_key, cmc_name:row.cmc_name,  cmc_sort:row.cmc_sort,_id:row._id}
  groupVisible.value = true
}
const groupDelL = (row)=>{
  ElMessageBox.confirm(
    `确认要删除"${row.cmc_name}"分组吗`,
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async() => {
      const res=  await modelGroupDel(`${row.cmc_key}/${row._id}`)
      console.log(res);
      if(res.code==200){
        ElMessage.success('删除成功')
        await getGroupList()
      }


    })
    .catch(() => {
    })
}
/* 列表中操作点击事件  */
const modelEditBtn = (row)=>{
  modelTitle.value = '编辑模型'
  console.log(row);
  modelVisible.value = true;
  modelForm.value={ cme_key: row.cme_key, cme_name: row.cme_name,  cme_icon: row.cme_icon,   cmc_key:row.cmc_key,cmc_name: row.cmc_name,  cme_type:row.cme_type,_id:row._id   ,cme_port:row.cme_port ,serviceType:row.serviceType    }
  console.log(modelForm.value);

}
const modelDelBtn = (row)=>{
  ElMessageBox.confirm(
    `确认要删除"${row.cme_name}"模型吗`,
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async() => {
      const res=  await modelDel(`${row.cmc_key}/${row._id}`)
      console.log(res);
      if(res){
        ElMessage.success('删除成功')
        await getGroupList()
      }


    })
    .catch(() => {
    })
}
/* 所属分组选中事件 */
const selectGroup = (item)=>{
  console.log(item);
  modelForm.value.cmc_name  = item.cmc_name
}
const selectType = (e)=>{
  modelForm.value.cmc_type_name  = e
  modelForm.value.serviceType = ''
}



/* 打开抽屉  模型详情 */
const openModelDetail = async(row)=>{
  console.log(row);
  model_id.value = row._id
  drawerVisible.value = true
  nextTick(async()=>{
    await modelDetailRef.value.getModelDetail()
  })
}


const getGroupList = async()=>{
 const res=  await modelGroupList({})
 console.log(res);
 groupList.value = res.data

}


getGroupList()
// 模型详情
const drawerVisible = ref(false);
</script>

<style scoped lang="scss">
.model {
  padding: 8px;
  .el-card {
  }
  .content-tree {
    ul {
      li {
        margin-top: 20px;
        .el-card {
          border: 1px solid #fff;
          margin: 10px 10px 0 0;
          :deep(.el-card__body) {
            padding: 15px !important;
            display: flex;
            align-items: center;
            > div:nth-child(1) {
              img {
                width: 52px;
                height: 52px;
              }
            }
            > div:nth-child(2) {
              padding: 0 12px;
              height:40px;
              display:flex;
              justify-content: space-between;
              align-items: center;
              span:nth-child(1) {
                font-size: 14px;
              }
              span:nth-child(2) {
                font-size: 12px;
              }
            }
          }
        }
      }
    }
  }
  .el-overlay .el-overlay-dialog .el-dialog {
    margin: 0;
  }
}

ul {
  margin: 0;
  padding: 0;
  li {
    list-style: none;
  }
}

.icon-list {
  display: flex;
  flex-wrap: wrap;
  padding-left: 10px;
  margin-top: 10px;

  .icon-item {
    cursor: pointer;
    // width: 5%;
    margin: 0 10px 10px 0;
    padding: 5px;
    display: flex;
    flex-direction: column;
    justify-items: center;
    align-items: center;
    border: 1px solid #ccc;
    &:hover {
      border-color: var(--el-color-primary);
      color: var(--el-color-primary);
      transition: all 0.2s;
      transform: scaleX(1.1);
    }
  }
  .active {
    border-color: var(--el-color-primary);
    color: var(--el-color-primary);
  }
}
</style>
